import logging
import multiprocessing
from datetime import datetime, timedelta

import pymysql
import sys

sys.path.append('/azitai/pyscript')

from calc.StockStrategy import StockStrategy

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s | %(filename)s - {%(lineno)d} - [%(levelname)s] - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S', encoding='utf-8')

mysql_host = "127.0.0.1"
mysql_port = 3306

logging.info("prepare database connect")


def execute_value(list):
    # create mysql connect
    connect = pymysql.connect(host=mysql_host, port=mysql_port, user='root', passwd='hxsoft.net', database='stock')
    cursor = connect.cursor()
    for stock_code in list:
        execute_sql = ("select a.stock_code code,stock_name name,b.stock_date date,b.`open` open,"
                       "b.`close` close,b.high high,b.low low,b.vol vol, b.pchange pchange,"
                       "c.zl1,c.zl2,c.ma5,c.ma10,c.ma20 ,c.ma30 ,c.ma60 ,c.v5 ,c.v10 ,c.v20,"
                       "c.dif ,c.dea,c.macd,c.kdj_k ,c.kdj_d ,c.kdj_j ,c.rsi_6 ,c.atr_14 "
                       "from stock_code a,stock_details b,stock_value c where a.stock_code = b.stock_code "
                       "and b.stock_code = c.stock_code and b.stock_date = c.stock_date "
                       "and b.stock_code = '%s' and b.stock_date >= '2018-01-01'" % stock_code)

        cursor.execute(execute_sql)
        list = cursor.fetchall()
        logging.info("stock_code: {} data list fetch successful: {}".format(stock_code, len(list)))

        if len(list) > 0:
            start_date = list[0][2]
            strategy = StockStrategy(data_list=list)
            date_list = []
            date = datetime.strptime("2019-01-01", "%Y-%m-%d")

            if start_date < date.date():
                date1 = datetime.strptime(start_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
                if date1 + timedelta(days=60) < date:
                    date = datetime.strptime("2019-01-01", "%Y-%m-%d")
                else:
                    date = date1 + timedelta(days=60)
            else:
                date = datetime.strptime(start_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
                date = date + timedelta(days=60)

            for i in range(5000):
                new_date = date + timedelta(days=i)
                if new_date <= datetime.strptime("2025-11-20", "%Y-%m-%d"):
                    dayTime = strategy.strategy(dayTime=new_date.strftime("%Y-%m-%d"))
                    if dayTime is not None:
                        date_list.append(dayTime)
                else:
                    break

            if len(date_list) > 0:
                for dayTime in date_list:
                    execute_sql = ("update stock_value set flag = 1 where stock_code = '%s' and stock_date = '%s'" % (
                        stock_code, dayTime))
                    cursor.execute(execute_sql)
                    logging.info("stock_code: {}, stock_date: {} update successful".format(stock_code, dayTime))
                connect.commit()
    cursor.close()
    connect.close()


if __name__ == '__main__':
    # create mysql connect
    connect1 = pymysql.connect(host=mysql_host, port=mysql_port, user='root', passwd='hxsoft.net', database='stock')
    cursor1 = connect1.cursor()
    cursor1.execute("select stock_code from stock_code")

    row_list = cursor1.fetchall()

    list1 = []
    list2 = []
    list3 = []

    row_index = 0
    for row in row_list:
        stock_code = row[0]
        if row_index % 3 == 0:
            list1.append(stock_code)
        elif row_index % 3 == 1:
            list2.append(stock_code)
        else:
            list3.append(stock_code)
        row_index = row_index + 1

    logging.info("list1 size: {}".format(len(list1)))
    logging.info("list2 size: {}".format(len(list2)))
    logging.info("list3 size: {}".format(len(list3)))

    processes = []
    for i in range(3):
        if i == 0:
            p = multiprocessing.Process(target=execute_value, args=(list1,))
        elif i == 1:
            p = multiprocessing.Process(target=execute_value, args=(list2,))
        else:
            p = multiprocessing.Process(target=execute_value, args=(list3,))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    cursor1.close()
    connect1.close()
